// json转树
function transformTozTreeFormat(sNodes) {
	sNodes = $.parseJSON(sNodes);
	var i, l, key = "id", parentKey = "parentId", childKey = "child";
	if (!key || key == "" || !sNodes)
		return [];
	var r = [];
	var tmpMap = [];
	for (i = 0, l = sNodes.length; i < l; i++) {
		tmpMap[sNodes[i][key]] = sNodes[i];
	}
	for (i = 0, l = sNodes.length; i < l; i++) {
		if (tmpMap[sNodes[i][parentKey]]
				&& sNodes[i][key] != sNodes[i][parentKey]) {
			if (!tmpMap[sNodes[i][parentKey]][childKey])
				tmpMap[sNodes[i][parentKey]][childKey] = [];
			tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
		} else {
			r.push(sNodes[i]);
		}
	}
	return r;
}

// 展示收缩
function itemwind(id, style) {
	$("tr[parentId='" + id + "']").each(
			function(i, v) {
				if (style == 'none') {
					if ($(v).attr('node') != ''
							&& $(v).attr('node') != undefined) {
						$(v).find("td").eq(1).find('img').attr('src',
								'images/g_addJia.png');
					}
				}
				$(v).css('display', style);
				var ids = $(this).attr('id');
				itemwind(ids, style);
			});
}
$.bsgrid.forcePushPropertyInObject(
		$.fn.bsgrid.defaults.extend.renderPerRowMethods,
		'extend_render_per_row', function(record, rowIndex, trObj, options) {
			if (record != undefined && record != '') {
				trObj.attr('id', record.id);
			}
			// trObj.find("td").first().css('text-align','left');
			if (record.node != undefined) {
				switch (record.node) {
				case 0:
					trObj.attr('class', 'parent0');
					trObj.attr('node', 0);
					break;
				case 1:
					trObj.attr('class', 'parent1');
					trObj.attr('node', 1);
					break;
				case 2:
					trObj.attr('class', 'parent2');
					trObj.attr('node', 2);
					break;
				case 3:
					trObj.attr('class', 'parent3');
					trObj.attr('node', 3);
					break;
				case 4:
					trObj.attr('class', 'parent4');
					trObj.attr('node', 4);
					break;
				}

			}else{
               trObj.attr('class','parent_left');
            }
			if (record != undefined && record != '' && record.parentId != ''
					&& record.parentId != undefined) {
				trObj.attr('parentId', record.parentId);
				// trObj.attr('class','parent_class');
			}
		});
var sdfs = [];
$(function() {
	search('');
});
function getItemData(data, parentId, level) {
	if (typeof (data) == "object") {
		$.each(data, function(i, n) {
			if (parentId != 0) {
				n.parentId = parentId;
			}
			if (n.child != undefined && n.child != ""
					&& typeof (n.child) == 'object') {
				// console.log(n.child);
				n.node = level;
				sdfs.push(n);
				getItemData(n.child, n.id, level + 1);
			} else {
				sdfs.push(n);
			}
		});
	}
}
function search(orgName){
	$("#g_tabYeh").html("<tr><th w_check=\"true\" w_index=\"id\" id=\"qx\"></th><th w_index=\"orgNo\" >组织编号</th><th w_index=\"orgName\" >组织名称</th><th w_render=\"operate\" >操作</th></tr>");
	sdfs = [];
	gridObj = $.fn.bsgrid.init('g_tabYeh', {
		/*
		 * dataType: 'json', ajaxType: 'post', url: '/user/getuserlist1',
		 */
		autoLoad : true,
		pageSizeSelect : false,
		stripeRows : true,
		pageSize : 99999999,
		displayBlankRows : false,
		isProcessLockScreen : true,
		rowSelectedColor : false,
		showPageToolbar : false
	});

	var userdatas = [];
	userdatas.success = true;
	userdatas.curPage = 1;
	var data_formate = '{"data":{"total":6,"curPage":1,"rows":';
	$.ajax({
		type : 'post',
		url : server_url + '/rest/organization/getorgls.do?token='+token+'&ran='+Math.random(),
		data:{orgName:orgName},
		async:false,
		success : function(data) {
			if(data.retCode=='0000'){
				var datastr = transformTozTreeFormat(data.data);
				var treejson = JSON.stringify(datastr);
				data_formate = data_formate+ treejson;
			}else{
				easyDialog.open({
					container:{
						header:'错误提示',
						content:'系统异常'
					},
					autoClose : 2000
				});
				console.error(data.retMsg);
			}
		}
	});
	data_formate = data_formate + '},"retCode":"0000","retMsg":"\u64cd\u4f5c\u6210\u529f"}';
	userdata = $.parseJSON(data_formate);
	getItemData(userdata.data.rows, 0, 0);
	userdatas.totalRows = sdfs.length;
	userdatas.data = sdfs;
	gridObj.loadGridData('json', userdatas);
	$('.parent0')
			.each(
					function() {
						var html_text = $(this).find("td").eq(1).html();
						html_text = '<div style="text-align:left;"><img src="images/g_remoJian.png" style="padding-left:8px;"/><span style="padding-left:10px;">'
								+ html_text + '</span></div>';
						$(this).find("td").eq(1).html(html_text);
						var id = $(this).attr('id');
						$("tr[parentId='" + id + "']")
								.each(
										function(i, v) {
											if ($(v).attr('node') == ''
													|| $(v).attr('node') == undefined) {
												var html_text = $(v).find("td")
														.eq(1).html();
												html_text = '<div style="text-align:left;"><span style="padding-left:40px;">'
														+ html_text
														+ '</span></div>';
												$(this).find("td").eq(1).html(
														html_text);
											}
											$(v).find("td").eq(1).css(
													'padding-left', '30px');

										});
					});
	$('.parent1')
			.each(
					function() {
						var html_text = $(this).find("td").eq(1).html();
						html_text = '<div style="text-align:left;"><img src="images/g_remoJian.png" style="padding-left:10px;"/><span style="padding-left:12px;">'
								+ html_text + '</span></div>';
						$(this).find("td").eq(1).html(html_text);
						var id = $(this).attr('id');
						$("tr[parentId='" + id + "']")
								.each(
										function(i, v) {
											if ($(v).attr('node') == ''
													|| $(v).attr('node') == undefined) {
												var html_text = $(v).find("td")
														.eq(1).html();
												html_text = '<div style="text-align:left;"><span style="padding-left:43px;">'
														+ html_text
														+ '</span></div>';
												$(this).find("td").eq(1).html(
														html_text);
											}
											$(v).find("td").eq(1).css(
													'padding-left', '60px');

										});
					});
	$('.parent2')
			.each(
					function() {
						var html_text = $(this).find("td").eq(1).html();
						html_text = '<div style="text-align:left;"><img src="images/g_remoJian.png" style="padding-left:12px;"/><span style="padding-left:14px;">'
								+ html_text + '</span></div>';
						$(this).find("td").eq(1).html(html_text);
						var id = $(this).attr('id');
						$("tr[parentId='" + id + "']")
								.each(
										function(i, v) {
											if ($(v).attr('node') == ''
													|| $(v).attr('node') == undefined) {
												var html_text = $(v).find("td")
														.eq(1).html();
												html_text = '<div style="text-align:left;"><span style="padding-left:46px;">'
														+ html_text
														+ '</span></div>';
												$(this).find("td").eq(1).html(
														html_text);
											}
											$(v).find("td").eq(1).css(
													'padding-left', '90px');

										});
					});
	$('.parent3')
			.each(
					function() {
						var html_text = $(this).find("td").eq(1).html();
						html_text = '<div style="text-align:left;"><img src="images/g_remoJian.png" style="padding-left:14px;"/><span style="padding-left:16px;">'
								+ html_text + '</span></div>';
						$(this).find("td").eq(1).html(html_text);
						var id = $(this).attr('id');
						$("tr[parentId='" + id + "']")
								.each(
										function(i, v) {
											if ($(v).attr('node') == ''
													|| $(v).attr('node') == undefined) {
												var html_text = $(v).find("td")
														.eq(1).html();
												html_text = '<div style="text-align:left;"><span style="padding-left:49px;">'
														+ html_text
														+ '</span></div>';
												$(this).find("td").eq(1).html(
														html_text);
											}
											$(v).find("td").eq(1).css(
													'padding-left', '120px');

										});
					});
	$('.parent4')
			.each(
					function() {
						var html_text = $(this).find("td").eq(1).html();
						html_text = '<div style="text-align:left;"><img src="images/g_remoJian.png" style="padding-left:16px;"/><span style="padding-left:18px;">'
								+ html_text + '</span></div>';
						$(this).find("td").eq(1).html(html_text);
						var id = $(this).attr('id');
						$("tr[parentId='" + id + "']")
								.each(
										function(i, v) {
											if ($(v).attr('node') == ''
													|| $(v).attr('node') == undefined) {
												var html_text = $(v).find("td")
														.eq(1).html();
												html_text = '<div style="text-align:left;"><span style="padding-left:52px;">'
														+ html_text
														+ '</span></div>';
												$(this).find("td").eq(1).html(
														html_text);
											}
											$(v).find("td").eq(1).css(
													'padding-left', '150px');

										});
					});

    for (var i = 0; i <5; i++) {
        $("tr[class='parent"+i+"']").each(function(p,k){
            $(k).find('td').eq(1).bind('click',function(){
                  var id=$(this).parent().attr('id');
                        if($(this).find('img').attr('src')=='images/g_remoJian.png'){
                           itemwind(id,'none');
                          $(this).find('img').attr('src','images/g_addJia.png');
                      }else{
                         $("tr[parentId='"+id+"']").each(function(i,v){
                            $(v).css('display','');
                          });
                        $(this).find('img').attr('src','images/g_remoJian.png');
                      }
            });
        });
      }             
    $("tr[class='parent_left']").each(function(pp,kk){
          if($(kk).attr('parentId')=='0' || $(kk).attr('parentId')==undefined || $(kk).attr('parentId')==''){
              var html_text=$(kk).find("td").eq(1).html();
           html_text ='<div style="text-align:left;"><span style="padding-left:25px;width:25px;height:17px;"></span><!--<img src="/public/images/g_remoJian.png" style="padding-left:8px;"/>--><span style="padding-left:10px;">'+html_text+'</span></div>';
            $(kk).find("td").eq(1).html(html_text);
          }
      });
	$('#qx').append('<span style="padding-left:5px;">全选</span>');
	$('.l_pageUpDown').hide();
}
function operate(record, rowIndex, colIndex, options) {
	return '<a href="javascript:EditUser(\''
			+ gridObj.getRecordIndexValue(record, 'id')
			+ '\');">编辑</a>';
}
function sex_operate(record, rowIndex, colIndex, options) {
	if (1 == gridObj.getRecordIndexValue(record, 'sex')) {
		return "男";
	} else {
		return "女";
	}
}
// 获取checkbox选中
function getCheckedIds() {
	// values are array
	alert(gridObj.getCheckedValues('id'));
}
// 数据表格参数查询
function doSearch() {
	var orgName = $('#username').val();
	search(orgName);
	//console.log(searchParames);
}

function getEnter(e){
	if(e && e.keyCode=='13'){
		doSearch();
	}
}
//编辑
function EditUser(id){
	var url = 'orgEdit.do?id='+id;
	tl_config.loadToWorkArea(url);
}
function toAdd(){
	url = "orgAdd.do"; 
	tl_config.loadToWorkArea(url);
}

/**
 * dialog弹出框
 */
var tmpid;
var toDel = function(e){
	var username=localStorage.getItem("username");
	$.ajax({
		type:'post',
		url:server_url+'/rest/organization/delorg.do?ran='+Math.random()+'&token='+token,
		data:{idLs:tmpid,modifyUser:username},
		success:function(data){
			if(data.retCode==="0000"){
				var idLs = $.parseJSON(data.data);
				for(var i in idLs){
					$("#"+idLs[i]).remove();
				}
			}else{
				easyDialog.open({
					container:{
						header:'温馨提示',
						content:'系统异常'
					},
					autoClose : 2000
				});
				console.error(data.retMsg);
			}
		},
		error:function(error,request,text){
			easyDialog.open({
				container:{
					header:'温馨提示',
					content:'系统异常'
				},
				autoClose : 2000
			});
			console.error(error);
		}
	});
	return true;
};


//批量删除
function DelUsers(){
	var idLs = [];
	var ids = [];
	$(".bsgrid_editgrid_check").each(function(){
		if($(this).attr("checked")){
			if($(this).val()!=''&&$(this).val!=undefined&&$(this).val()!='on'){
				idLs.push($(this).val());
				ids.push($(this).val());
			}
		}
	});
	getChildIds(ids,idLs);
	var idStr = arrayToString(idLs,';');
	if(idStr===''){
		easyDialog.open({
			container:{
				header:'温馨提示',
				content:'请选择要删除的组织!'
			},
			autoClose : 2000
		});
	}else{
		tmpid = idStr;
		easyDialog.open({
			container:{
				header:'温馨提示',
				content:'您将删除该组织以及下面所有的子组织<br>确定删除吗？',
				yesFn:toDel,
				noFn:true
			}
		});
	}
}
//获取选中的节点及其子节点的id
function getChildIds(ids,idLs){
	var id = [];
	for(var i in ids){
		$("tr[parentid='" + ids[i] + "']").each(function(){
			idLs.push($(this).attr("id"));
			id.push($(this).attr("id"));
		});
	}
	if(id.length>0){
		getChildIds(id,idLs);
	}
}
//按照某个字符串将数组拼成字符串
function arrayToString(arr,separator)
{
if(!separator) separator = "";//separator为null则默认为空
    return arr.join(separator); 
}